#include "CLich_Attack_Effect.h"
#include "CUnit.h"

#include "Enum.h"

#include "Utility.h"
#include "Animation.h"
#include "SpriteMaker.h"

int const LICH_ATTACK_EFFECT_HLAF_WIDTH = 70;
int const LICH_ATTACK_EFFECT_HLAF_HEIGHT = -75;
int const LICH_ATTACK_EFFECT_MOVE_DELAY = 300;
int const LICH_ATTACK_EFFECT_MOVE_X = -20;
int const LICH_RANGE = 20;
int const UNIT_HALF_WIDTH = 40;

int const DOWN_Y = 20;

CLich_Attack_Effect::CLich_Attack_Effect(int _nX, int _nY, int _nTargetX, int _nDamage, ls_Unit* _pEnumy, CBuilding* _pBuilding, int _nNumber)
{
	m_nX = _nX;
	m_nY = _nY - DOWN_Y;
	m_nTargetX = _nTargetX;
	m_nDamage = _nDamage;
	m_pEnumy = _pEnumy;
	m_nNumber = _nNumber;
	m_pEnumyBuilding = _pBuilding;
	m_nMaxAttackCount = 4;
	m_nNowAttackCount = 0;

	SharedSpriteMaker.createAnimation("Lich_Attack_Effect", m_nNumber);
	SharedSpriteMaker.getAnimation(m_nNumber)->setGrid(4,1);
	SharedSpriteMaker.getAnimation(m_nNumber)->setSize(LICH_ATTACK_EFFECT_HLAF_WIDTH, (-LICH_ATTACK_EFFECT_HLAF_HEIGHT));
	SharedSpriteMaker.getAnimation(m_nNumber)->setSpeed(1.0f);
	SharedSpriteMaker.getAnimation(m_nNumber)->setPosition(-100000, 100000, m_nNumber);

	m_nFinalTime = OgrePlugin_2DRenderer::getPlatformTime() + LICH_ATTACK_EFFECT_MOVE_DELAY;
}

CLich_Attack_Effect::~CLich_Attack_Effect(void)
{
	SharedSpriteMaker.removeAnimation(m_nNumber);
}

void CLich_Attack_Effect::put(void)
{
	SharedSpriteMaker.getAnimation(m_nNumber)->setPosition(m_nX, m_nY, 100);
}

int CLich_Attack_Effect::run(void)
{
	m_nNowTime = OgrePlugin_2DRenderer::getPlatformTime();
	if(0 >= m_nFinalTime - m_nNowTime)
	{
		++m_nNowAttackCount;
		SharedSpriteMaker.getAnimation(m_nNumber)->run(1.0f);

		m_nFinalTime = OgrePlugin_2DRenderer::getPlatformTime() + LICH_ATTACK_EFFECT_MOVE_DELAY;
		if(m_nMaxAttackCount == m_nNowAttackCount)
		{
			m_itr = m_pEnumy->begin();
			int EnumyX;
			while(m_itr != m_pEnumy->end())
			{
				EnumyX = (*m_itr)->GetX();
				if(m_nX - LICH_RANGE <= EnumyX - UNIT_HALF_WIDTH)
				{
					if(m_nX + LICH_RANGE >= EnumyX - UNIT_HALF_WIDTH)
					{
						if(m_nY + DOWN_Y == (*m_itr)->GetY())
						{
							(*m_itr)->Hit(m_nDamage, eMagician);
						}
					}
				}
				++m_itr;
			}
			if(m_nX <= m_pEnumyBuilding->GetX())
			{
				m_pEnumyBuilding->Hit(m_nDamage);
			}
			return -1;
		}
	}

	else
	{
		return 1;
	}
}